<?php
namespace Api\Controller;
use Api\Controller\CommonController;
class OrderController extends CommonController {
	public function _initialize(){
		parent::_initialize();
		 
		//登录验证
		$this->_checkLogin();
	}
	public function checkGoodsdesc(){
		$data=array(
			"count"=>intval(I("count")),
			"goodsID"=>I("goodsID"),
			"goodsNum"=>I("goodsNum"),
		);
		if(!isNotEmptyArr($data)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		$goodsIDArr=explode(",", $data['goodsID']);
		//$goodsNumArr=explode(",", $data['goodsNum']);
		//if(!(count($goodsIDArr)==$data['count'] && count($goodsNumArr)==$data['count'] && count($goodsIDArr)==count($goodsNumArr))){
		//	$this->_returnJson(array("result"=>0,"info"=>"error data","code"=>"127"));
		//}
		foreach ($goodsIDArr as $key=>$a){
			$isGoods=D("Goods")->getGoods($a,array("isOn"=>1));
			if($isGoods['goods_desc']){
				$info = $isGoods['goods_desc'];
				$this->_returnJson(array("result"=>0,"info"=>$info));
			}
		}
		$this->_returnJson(array("result"=>1,"info"=>"没有商品限制销售信息"));
	}
	
	/**
	 *  下单
	 */
	public function add(){
		$data=array(
			"count"=>intval(I("count")),
			"goodsID"=>I("goodsID"),
			"goodsNum"=>I("goodsNum"),
		);
		
		if(!isNotEmptyArr($data)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		
		$goodsIDArr=explode(",", $data['goodsID']);
		$goodsNumArr=explode(",", $data['goodsNum']);
		if(!(count($goodsIDArr)==$data['count'] && count($goodsNumArr)==$data['count'] && count($goodsIDArr)==count($goodsNumArr))){
			$this->_returnJson(array("result"=>0,"info"=>"error data","code"=>"127"));
		}
		
		isset($_POST['goodsType'])&&in_array(intval(I("goodsType")),array("0","1"))?$orderType=intval(I("goodsType")):$orderType=1;
		
		//收货地址
		$addressID = intval(I("post.addressID"));
		$addressID=empty($addressID)?0:intval(I("post.addressID"));
		if($addressID!=0){
			$address=D("UserAddress")->where(array("userID"=>$this->user['uid'],"isOn"=>1,"addressID"=>$addressID))->find();
			if(!$address) $this->_returnJson(array("result"=>0,"info"=>"no data","code"=>"141"));
		}
		
		/* if($orderType=="0"){
		    //检测收货地址
		    empty(intval(I("post.addressID"))) ? $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123")) : $addressID=intval(I("post.addressID"));
		    $address=D("UserAddress")->where(array("userID"=>$this->user['uid'],"isOn"=>1,"addressID"=>$addressID))->find();
            if(!$address) $this->_returnJson(array("result"=>0,"info"=>"no data","code"=>"141"));		
		} */
		
		$shopIDArr=array();
		$goodsArr=array();
		$totalGoodsPrice=0;
		$totalMarketPrice=0;
		foreach ($goodsIDArr as $key=>$a){
			//检测商品是否存在可用
			$isGoods=D("Goods")->getGoods($a,array("isOn"=>1));
			//不存在商品
			if(!$isGoods) $this->_returnJson(array("result"=>0,"info"=>"goods is not exist","goodsID"=>$a,"code"=>"128"));
			//商品已下架
			if($isGoods['isSale']!=1) $this->_returnJson(array("result"=>0,"info"=>"goods down","goodsID"=>$a,"code"=>"129"));
			//商品类型是否和订单类型相同
			if($isGoods['commentType']!=$orderType) $this->_returnJson(array("result"=>0,"info"=>"error data","code"=>"127"));
			
			//取出购买数量
			$num=$goodsNumArr[$key];
			if($num < 1) $this->_returnJson(array("result"=>0,"info"=>"error goodsNum","goodsID"=>$a,"code"=>"132"));
			
			//是否限时购买
			if($isGoods['isTimeLimit']==1){
				if(time() < $isGoods['limitStartTime']){
					$this->_returnJson(array("result"=>0,"info"=>"error goods time","goodsID"=>$a,"code"=>"150"));
				}
				elseif(time() > $isGoods['limitEndTime']){
					$this->_returnJson(array("result"=>0,"info"=>"error goods time","goodsID"=>$a,"code"=>"151"));
				}
			}
			
			//是否有库存
			//dump($isGoods['num'] );
			if(!($isGoods['num'] < 0 )){
				if( $isGoods['restNum'] < $num){
					$this->_returnJson(array("result"=>0,"info"=>"The restNum is not enough ","goodsID"=>$a,"code"=>"146"));
				}
			}
			
			//限购
			if($isGoods['limitNum'] >= 0){
			    $goodsLogNum=D('OrderGoods')->field('sum(num) as num')->where(array('userID'=>$this->user['uid'],"status"=>1,"goodsID"=>$a,'isOn'=>1))->find();
			    if(($goodsLogNum['num'] +$num) > $isGoods['limitNum']){
			    	$this->_returnJson(array("result"=>0,"info"=>"Beyond the purchase quantity","goodsID"=>$a,'orderGoodsNum'=>$goodsLogNum,'limitNum'=>$isGoods['limitNum'],"code"=>"147"));
			    }
			}
			//月限购
			
			if($isGoods['monthLimitNum'] >= 0){
				$start=strtotime(date('Y-m-01 00:00:00'));
				$end = strtotime(date('Y-m-d H:i:s'));
				$goodsLogNum=D('OrderGoods')->field('sum(num) as num')->where(array('userID'=>$this->user['uid'],"status"=>1,"goodsID"=>$a,'isOn'=>1))->where(array('addTime'=>array('between',array($start,$end))))->find();
			    if(($goodsLogNum['num'] +$num) > $isGoods['monthLimitNum']){
			    	$this->_returnJson(array("result"=>0,"info"=>"Beyond the month purchase quantity","goodsID"=>$a,'orderGoodsNum'=>$goodsLogNum,'monthlimitNum'=>$isGoods['monthLimitNum'],"code"=>"148"));
			    }
			}
			
			/*if($isGoods['goods_desc']){
				$this->_returnJson(array("result"=>0,"info"=>$isGoods['goods_desc'],"goodsID"=>$a,"code"=>"154"));
			}*/
			
			if (!in_array($isGoods['shopID'], $shopIDArr)) {
				//查询对应商店是否开启
				$isShop=D("Shop")->getShop("",$isGoods['shopID'],array("isOn"=>1));
				//不存在商店
				if(!$isShop) $this->_returnJson(array("result"=>0,"info"=>"shop is not exist","shopID"=>$isGoods['shopID'],"code"=>"130"));
				//商店已关闭
				if($isShop['isWork']!=1) $this->_returnJson(array("result"=>0,"info"=>"shop down","shopID"=>$a,"code"=>"131"));
				$shopIDArr[]=$isGoods['shopID'];
			}
			$cat=D("GoodsCat")->getGoodsCat($isGoods['catID'],array("isOn"=>1));
			
			if(empty($cat['code'])&&$addressID==0){
				$this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
			}
			
			$isGoods['catDetail']=$cat;
			
			$isGoods['num']=$num;
			$isGoods['city']=$isShop['city'];
			$isGoods['province']=$isShop['province'];
			$totalGoodsPrice+=$isGoods['goodsPrice']*$num;
			$totalMarketPrice+=$isGoods['marketPrice']*$num;
			$goodsArr[]=$isGoods;
		}
		
		//--记录数据库
		D()->startTrans();
		
		//生成订单
		$orderSn=date('ymd').substr(time(),-5).substr(microtime(),2,5).rand(100,999);
		$order=array(
			"userID"=>$this->user['uid'],
			"orderSn"=>$orderSn,
			"totalPrice"=>$totalMarketPrice,
			"payPrice"=>$totalGoodsPrice,
			"addTime"=>time(),
		    "orderType"=>$orderType
		);
		
		if($address){
		    $order['province']=$address['province'];
		    $order['city']=$address['city'];
		    $order['district']=$address['district'];
		    $order['address']=$address['address'];
		    $order['zcode']=$address['zcode'];
		    $order['consignee']=$address['consignee'];
		    $order['phone']=$address['phone'];
		}
		
		$addOrder=D("Order")->addOrder($order);

		file_put_contents("payLog/orderinfo_".date("Ymd").".txt", json_encode($order,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);

		//dump($addOrder);exit;
		if(!$addOrder){
			D()->rollback();
			$this->_returnJson(array("result"=>0,"info"=>"system error","code"=>"105"));
		}
		
		foreach ($goodsArr as $a){
		    if (!empty($a['catDetail']['code'])){//服务商品调用预下单接口
				if($a['catDetail']['code']!="virtualCode"){
					$result=$this->_orderCouponPre($a['catDetail']['code'], $a['num'], $this->user['mobileNum'],$this->_getAreaNum($a['province'],$a['city']));//
				}
		        else {
					$result=true;
				}
		        if (!$result) {
		            D()->rollback();
		            $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>$this->apiErrorMsg,"code"=>"119") );
		        }
		    }
			
			
			$apiOrderSn=$result['orderSn'];
			
			//写入订单商品
			$orderGoodsData=array(
				"shopID"=>$a['shopID'],
				"orderID"=>$addOrder,
				"goodsID"=>$a['goodsID'],
				"goodsName"=>$a['goodsName'],
				"userID"=>$this->user['uid'],
				"orderSn"=>$orderSn,
				"apiOrderSn"=>$apiOrderSn,
				"maketPrice"=>$a['maketPrice'],
				"goodsPrice"=>$a['goodsPrice'],
				"comtPrice"=>$a['goodsPrice']*$a['num'],
				"num"=>$a['num'],
				"unit"=>$a['unit'],
				"catID"=>$a['catID'],
				"catName"=>$cat['catName'],
				"commentType"=>$cat['commentType'],
				"phone"=>$this->user['mobileNum'],
				"addTime"=>time()
			);
			
			$addOrderGoods=D("OrderGoods")->addOrderGoods($orderGoodsData);
			if(!$addOrderGoods){
				D()->rollback();
				$this->_returnJson(array("result"=>0,"info"=>"system error","code"=>"105"));
			}
		}
		D()->commit();
		$this->_returnJson(array("result"=>1,"orderSn"=>$orderSn));
	}
	
	public function confirmOrder(){
	    $data=array(
    			"orderSn"=>I("orderSn"),
    	);
    	if(!isNotEmptyArr($data)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
    	//判断订单是否存在
    	$order=D("Order")->getOrder("",array("orderSn"=>$data['orderSn'],"userID"=>$this->user['uid'],"isOn"=>1));
    	//echo D()->getLastSql();
    	//dump($order);
    	if(!$order) $this->_returnJson(array("result"=>0,"info"=>"order is not exist","code"=>"133"));
    	//未支付
    	if($order['status']!=1) $this->_returnJson(array("result"=>0,"info"=>"order status error","code"=>"142"));
    	//未发货
    	if($order['logisticsStatus']!=1) $this->_returnJson(array("result"=>0,"info"=>"order status error","code"=>"142"));
	    $result=D("order")->save(array("status"=>2,"orderID"=>$order['orderID']));
	    if(!$result) $this->_returnJson(array("result"=>0,"info"=>"system error","code"=>"143"));
	    $this->_returnJson(array("result"=>1));
	}
	
}